import { ref } from 'vue'
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
import cache from '@/utils/cache';

export function usePugTagList() {
    // 获取当前页面请求的路由
    var route = useRoute();
    var router = useRouter();

    // 根据当前页，激活当前tag卡片
    const activeTab = ref(route.path)
        // 标签卡片数据
    const editableTabs = ref([{
        title: "后台首页",
        path: "/"
    }])

    // 初始化标签导航
    function initTableList() {
        let cacheMenuList = cache.local.get("editableTabs");
        if (cacheMenuList) {
            editableTabs.value = JSON.parse(cacheMenuList);
        }
    }

    initTableList();

    // 获取当前的路由更新监听
    onBeforeRouteUpdate((to, form) => {
        // 添加
        addTab({
                title: to.meta.title,
                path: to.path
            })
            // 激活当前
        activeTab.value = to.path;
    })


    // 添加标签
    const addTab = (tab) => {
        // 判断当前的抱歉是否已经在标签容器中
        var exisit = editableTabs.value.findIndex(item => item.path == tab.path) == -1
            // 如果不存在就添加
        if (exisit) {
            editableTabs.value.push(tab);
        }

        cache.local.set("editableTabs", JSON.stringify(editableTabs.value));
    }

    // 删除标签
    const removeTab = (targetName) => {
        // 获取所有的标签
        const tabs = editableTabs.value
            // 获取当前激活的标签
        let activeName = activeTab.value
            // 如果激活的标签当前删除的标签是一致
        if (activeName === targetName) {
            tabs.forEach((tab, index) => {
                if (tab.path === targetName) {
                    const nextTab = tabs[index + 1] || tabs[index - 1]
                    if (nextTab) {
                        activeName = nextTab.path
                    }
                }
            })
        }

        activeTab.value = activeName
        editableTabs.value = tabs.filter((tab) => tab.path !== targetName)

        cache.local.set("editableTabs", JSON.stringify(editableTabs.value));
    }


    // 点击标签跳转页面
    const changeTab = (tab) => {
        console.log(tab)
        activeTab.value = tab
        router.push(tab);
    }

    // 下拉关闭
    const handlerClose = (item) => {
        if (item == "closeAll") {
            editableTabs.value = [{
                title: "后台首页",
                path: "/"
            }]
            activeTab.value = "/"
        } else {
            editableTabs.value = editableTabs.value.filter(item => item.path == "/" || item.path == activeTab.value);
        }

        cache.local.set("editableTabs", JSON.stringify(editableTabs.value));
    }


    return {
        changeTab,
        handlerClose,
        removeTab,
        editableTabs,
        activeTab
    }

}